package com.leyou.upload.service;

import ch.qos.logback.core.util.ContentTypeUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.leyou.common.enums.LyExceptionEnum;
import com.leyou.common.exceptions.LyException;
import com.leyou.upload.config.OSSProperties;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Base64Utils;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.*;

@Service
public class UploadService {

    private static final Logger logger = LoggerFactory.getLogger(UploadService.class);

    // 支持的文件类型
    private static final List<String> suffixes = Arrays.asList("image/png", "image/jpeg", "image/bmp");

    public String uploadImage(MultipartFile file) {
        logger.info("UploadService--uploadImage--请求参数:" + file.getOriginalFilename());
        // 判断文件类型
        String contentType = file.getContentType();
        if (!suffixes.contains(contentType)) {
            throw new LyException(LyExceptionEnum.INVALID_FILE_TYPE);
        }

        // 判断图片内容是否存在
        BufferedImage image = null;
        try {
            image = ImageIO.read(file.getInputStream());
        } catch (IOException e) {
            throw new LyException(LyExceptionEnum.INVALID_FILE_TYPE);
        }
        if (image == null) {
            throw new LyException(LyExceptionEnum.INVALID_FILE_TYPE);
        }

        File dir = new File("D:\\devTools\\nginx-1.14.0\\html");
        if (!dir.exists()) {
            dir.mkdirs();
        }
        try {
            file.transferTo(new File(dir, file.getOriginalFilename()));
            return "http://image.leyou.com/" + file.getOriginalFilename();
        } catch (IOException e) {
            System.out.println(e);
            throw new LyException(LyExceptionEnum.FILE_UPLOAD_ERROR);
        }
    }

    @Autowired
    private OSS ossClient;

    @Autowired
    private OSSProperties ossProperties;

    public Map<String, Object> getSignature() {
        try {
            long expireTime = ossProperties.getExpireTime();
            long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            Date expiration = new Date(expireEndTime);
            System.out.println(expiration);

            PolicyConditions policyconditions = new PolicyConditions();
            policyconditions.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, ossProperties.getMaxFileSize());
            policyconditions.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, ossProperties.getDir());

            String postPolicy = ossClient.generatePostPolicy(expiration, policyconditions);
            byte[] binaryPostPolicy = postPolicy.getBytes("utf-8");
            String encodePolicy = Base64.encodeBase64String(binaryPostPolicy);  // BinaryUtil.toBase64String()
            String postSignature = ossClient.calculatePostSignature(postPolicy);

            Map<String, Object> respMap = new LinkedHashMap<>();
            respMap.put("accessId", ossProperties.getAccessKeyId());
            respMap.put("policy", encodePolicy);
            respMap.put("signature", postSignature);
            respMap.put("dir", ossProperties.getDir());
            respMap.put("host", ossProperties.getHost());
            respMap.put("expire", expireEndTime);
            return respMap;
        } catch (UnsupportedEncodingException e) {
            throw new LyException(LyExceptionEnum.UPDATE_OPERATION_FAIL);
        }
    }
}
